<?php
/**
 * User: Drery
 * Date: 2015/11/30
 * Time: 11:24
 */

namespace backend\models;

use Yii;
use yii\base\Model;

class LoginForm extends Model
{
    public $user_name;
    public $password;
    public $verify_code;
    public $_user=false;

    public function rules()
    {
        return [
            [['user_name','password','verify_code'],'required'],
            ['verify_code', 'captcha','captchaAction'=>'public/captcha'],
            ['user_name','string','max'=>16],
            ['password','string','length'=>[6,16]],
            ['password','match','pattern'=>'/[0-9]{1}/'],
            ['password','match','pattern'=>'/[a-z]{1}/'],
            ['password','match','pattern'=>'/[A-Z]{1}/'],
            ['user_name','validateUsername'],
            ['password','validatePassword'],
            ['user_name','validateUserInvalid']
        ];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'user_name' => '用户名',
            'password' => '密码',
            'verify_code' => '验证码',
        ];
    }

    public function validateUsername()
    {
        if (!$this->hasErrors()) {
            $this->getUser();
            if (!$this->_user) {
                $this->addError('user_name','用户名不存在');
            }
        }
    }

    public function validatePassword()
    {
        if (!$this->hasErrors()) {
            if (!Yii::$app->security->validatePassword($this->password,$this->getUser()->password)) {
                $this->addError('password','密码错误');
            }
        }
    }

    public function validateUserInvalid()
    {
        if (!$this->hasErrors()) {
            if (isset($this->_user->is_forbidden) && $this->_user->is_forbidden == 1) {
                $this->addError('user_name','此用户已禁用');
            } elseif (isset($this->_user->is_locked) && $this->_user->is_locked == 1) {
                $this->addError('user_name','此用户已被锁定');
            }
        }
    }

    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser());
        }
        return false;
    }

    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = Admin::findByUsername($this->user_name);
        }
        return $this->_user;
    }
}